package cn.live.kyle.questionnaire.question;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import cn.live.kyle.questionnaire.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class QuestionRadio extends QuestionItem {

	private NodeList mOptionList;

	private RadioGroup mRadioGroup;
	private int mAnswer = -1;

	public QuestionRadio(Element element, QuestionPage page) {
		super(element, page);

		ViewGroup container = page.getQuestionViewContainer();
		Context context = container.getContext();
		mQuestionItemView = LayoutInflater.from(context).inflate(
				R.layout.question_radio, container, false);
		mRadioGroup = (RadioGroup) mQuestionItemView
				.findViewById(R.id.radioGroup);

		String answer = mElement.getAttribute(QuestionDomParser.ATTR_ANSWER);
		if (answer != null && answer.length() > 0) {
			mAnswer = Integer.valueOf(answer);
			mIsAnswered = true;
		}

		mOptionList = mElement
				.getElementsByTagName(QuestionDomParser.TAG_OPTION);
		int optionCount = mOptionList.getLength();
		for (int i = 0; i < optionCount; i++) {
			RadioButton button = (RadioButton) (LayoutInflater.from(context)
					.inflate(R.layout.question_radio_button, mRadioGroup, false));
			mRadioGroup.addView(button);
			Element option = (Element) mOptionList.item(i);
			String title = option.getAttribute(QuestionDomParser.ATTR_TITLE);
			button.setText(title);

			if (i == mAnswer) {
				button.setChecked(true);
			}

			button.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton button,
						boolean checked) {
					if (checked) {
						mAnswer = mRadioGroup.indexOfChild(button);
						mElement.setAttribute(QuestionDomParser.ATTR_ANSWER,
								String.valueOf(mAnswer));
						mIsAnswered = true;
						mQuestionPage.onQuestionItemStateChanged();
						mQuestionPage.completePage();
					}
				}
			});
		}
	}

}
